//
//  PKPKPlayViewController.m
//  PianKe
//
//  Created by lanou on 15/10/6.
//  Copyright (c) 2015年 lanou. All rights reserved.
//

#import "PKPKPlayViewController.h"
#import "PKPlayListTableViewController.h"
#import "PKPlayerView.h"
#import "PKPlayerManager.h"
#import "PKRadioHostessOtherWorks.h"
#import "PKMainLessonMoreting.h"
#import "PKMainLessonModel.h"
#import "PKRequestManager.h"
#import "PKWebViewController.h"
@interface PKPKPlayViewController ()<UIScrollViewDelegate>
@property(nonatomic,strong)UIScrollView *mainScrollerView;
@property(nonatomic,strong)PKPlayListTableViewController *listTableViewController;
@property(nonatomic,strong)UIView *lineView;
@property(nonatomic,strong)PKPlayerView *playerView;
@property(nonatomic,strong)UIView *palyerControlView;
@property(nonatomic,strong)UIButton *beforeSongButton;
@property(nonatomic,strong)UIButton *pauseAndPlayButton;
@property(nonatomic,strong)UIButton *nextSongButton;
@property(nonatomic,strong)UIWebView *article;
@property(nonatomic,strong)NSString *webUrl;
@property(nonatomic,strong)PKRadioHostessOtherWorks *hostessOtherWorksView;
@property(nonatomic,strong)PKMainLessonModel *mainLessonModel;
@property(nonatomic,strong)PKMainLessonMoreting *mainLessonMoreting;
@property(nonatomic,strong)NSMutableArray *dataSourceArr;
@property(nonatomic,assign)NSInteger playIndexCount;

@end

@implementation PKPKPlayViewController
-(NSMutableArray *)musicArray
{
    if (_musicArray==nil) {
        self.musicArray=[NSMutableArray arrayWithCapacity:0];
    }
    return _musicArray;
}
-(NSMutableArray *)dataSourceArr
{
    if (_dataSourceArr==nil) {
        self.dataSourceArr=[NSMutableArray arrayWithCapacity:0];
    }
    return _dataSourceArr;
}

-(void)acquireData
{NSLog(@"%@",self.tingid);
    NSMutableDictionary *PKrequestDict=[NSMutableDictionary dictionary];
    PKrequestDict[@"auth"]=@"";
    PKrequestDict[@"client"]=@"1";
    PKrequestDict[@"deviceid"]=@"63A94D37-33F9-40FF-9EBB-481182338873";
    if (self.radioModel.tingid!=nil) {
        self.tingid=self.radioModel.tingid;
        
    }
   

    
    PKrequestDict[@"tingid"]=self.tingid;
    NSLog(@"%@",self.radioModel.tingid);
    PKrequestDict[@"version"]=@"3.0.4";
    
    [PKRequestManager requestWithType:POST urlString:@"http://api2.pianke.me/ting/info" patDic:PKrequestDict finish:^(NSData *data) {
        NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves error:nil];
        NSDictionary *smalldict=dict[@"data"];
        self.mainLessonModel=[[PKMainLessonModel alloc]init];
        [self.mainLessonModel setValuesForKeysWithDictionary:smalldict];
        
#warning 数据请求完成的时候改变播放页面的喜欢的数量和评论的数量
        _playerView.radionDetailModel=self.mainLessonModel;
        NSLog(@"like%ld",self.mainLessonModel.like);
        NSLog(@"comment%ld",self.mainLessonModel.comment);
        
        _playerView.commentNumLabel.text=[NSString stringWithFormat:@"%ld",self.mainLessonModel.comment ];
        _playerView.collectionNumLabel.text=[NSString stringWithFormat:@"%ld",self.mainLessonModel.like];
#warning 当数据解析完毕的时候把weburl传给UIWebView
        _webUrl=self.mainLessonModel.playInfo.webview_url;
         [_article loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.webUrl] cachePolicy: NSURLRequestUseProtocolCachePolicy timeoutInterval:0]];
        NSLog(@"%@",self.mainLessonModel.playInfo.webview_url);
#warning 解析完成后改变电台的名字
         _hostessOtherWorksView.radioDetailModel=self.mainLessonModel;
        _hostessOtherWorksView.fromRadioNameLabel.text=[NSString stringWithFormat:@"%@",self.mainLessonModel.radioname];
#warning 解析最后一个轮播图界面所需要的图片的model类
        
        
        
#warning 当解析成功的时候把数据传给hostView中的collectionView中
        
        
        for (NSDictionary *modelDict in  self.mainLessonModel.moreting) {
            self.mainLessonMoreting=[[PKMainLessonMoreting alloc]init];
            [self.mainLessonMoreting setValuesForKeysWithDictionary:modelDict];
            [self.dataSourceArr addObject:self.mainLessonMoreting];
            
        }
        _hostessOtherWorksView.hostessWorkCVC.datasourceArr=self.dataSourceArr;
        
        [_hostessOtherWorksView.hostessWorkCVC.collectionView reloadData];
#warning 当详情界面传过来的tingid等于空的时候让音乐的数组传给播放器
        if (self.radioModel.tingid==nil) {
            NSString *musicurl=self.mainLessonModel.playInfo.musicUrl;
            [self.musicArray addObject:musicurl];
            NSLog(@"%@",musicurl);
            self.songNumber=0;
            PKPlayerManager *manager=[PKPlayerManager shareManager];
            [manager setManagerMusicArray:self.musicArray];
            [manager playWithIndex:self.songNumber];
           
                NSString *title=self.mainLessonModel.playInfo.title;
                NSString *uname=self.mainLessonModel.userinfo.uname;
            self.listTableViewController.cell.titleLabel.text=title;
            self.listTableViewController.cell.usernameLabel.text=uname;
            [self.listTableViewController.tableView reloadData];
        
         
//            PKRadioDetailModel *radiomodel=[[PKRadioDetailModel alloc]init];
//            radiomodel.title=self.mainLessonModel.playInfo.title;
//            radiomodel.playInfo.userinfo.uname=self.mainLessonModel.playInfo.userinfo.uname;
//            NSMutableArray *datasourceArr=[NSMutableArray arrayWithCapacity:0];
//            [datasourceArr addObject:radiomodel];
//            self.listTableViewController.dataSourceArray=datasourceArr;
//            [self.listTableViewController.tableView reloadData];
            

        }

        
    } Error:^(NSError *error) {
        NSLog(@"电台收听数据解析失败");
    }];
}
-(void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBar.hidden=NO;
}
- (void)viewDidLoad {
   
    [super viewDidLoad];
     NSLog(@"--------%@",self.tingid);
    [self acquireData];
//     self.navigationController.navigationBar.hidden=YES;
    // Do any additional setup after loading the view.
    _mainScrollerView=[[UIScrollView alloc]initWithFrame:CGRectMake(0, 70, SCREEN_WIDTH, SCREEN_HEIGHT-140)];
    _mainScrollerView.contentSize=CGSizeMake(SCREEN_WIDTH*4, SCREEN_HEIGHT-140) ;
    _mainScrollerView.pagingEnabled=YES;
    _mainScrollerView.delegate=self;
    
    _listTableViewController =[[PKPlayListTableViewController alloc]init];
    _listTableViewController.dataSourceArray=self.dataSourceArray;
   
   
    
    _listTableViewController.tableView.frame=CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-140);
    [_mainScrollerView addSubview:_listTableViewController.tableView];
#warning 创建播放界面的View
    _playerView=[[PKPlayerView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH, 0, SCREEN_WIDTH, SCREEN_HEIGHT-140)];
   
    _playerView.backgroundColor=[UIColor whiteColor];
//    _playerView.radionDetailModel=self.radioModel;
    [_mainScrollerView addSubview:_playerView];
#warning 创建UIWebView
    _article=[[UIWebView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH*2, 0, SCREEN_WIDTH, SCREEN_HEIGHT-140)];
   
   
    [_mainScrollerView addSubview:_article];
#warning 创建主播其它作品的页面
    _hostessOtherWorksView=[[PKRadioHostessOtherWorks alloc]initWithFrame:CGRectMake(SCREEN_WIDTH*3, 0, SCREEN_WIDTH, SCREEN_HEIGHT-140)];
    __block PKPKPlayViewController *test=self;
    _hostessOtherWorksView.nextPageBlock=^(NSString *weburl)
    {
        PKWebViewController *webViewVC=[[PKWebViewController alloc]init];
        webViewVC.weburl=weburl;
        
        [test.navigationController pushViewController:webViewVC animated:YES];
        

    };
    _hostessOtherWorksView.hostessWorkCVC.ScucessClickCollectionItemBlcok=^(NSString *tingId,NSInteger songNumber)
    { test.radioModel.tingid=tingId;
        NSLog(@"+++++=我我%@",tingId);
           [test acquireData];
        test.mainScrollerView.contentOffset=CGPointMake(SCREEN_WIDTH, 0);
        NSMutableArray *musicToalArray=[NSMutableArray arrayWithCapacity:0];
        for (PKMainLessonMoreting *model in  test.dataSourceArr ) {
        
        NSString *musicUrl=model.playInfo[@"musicUrl"];
        NSLog(@"音乐播放得musicurl%@",model.playInfo[@"musicUrl"]);
       
        [musicToalArray addObject:musicUrl];
               }
        test.musicArray =musicToalArray;
        PKPlayerManager *manager=[PKPlayerManager shareManager];
        [manager setManagerMusicArray:test.musicArray];
        [manager playWithIndex:songNumber];

        NSMutableArray *arr=[NSMutableArray arrayWithCapacity:0];
        for (PKMainLessonMoreting *model in  test.dataSourceArr ) {
            PKRadioDetailModel *radioDetail=[[PKRadioDetailModel alloc]init];
//            [radioDetail.playInfo setValuesForKeysWithDictionary: model.playInfo];
            
            radioDetail.playInfo=[[PKPlayInfo alloc]init];
            radioDetail.playInfo.userinfo=[[PKUserInfo alloc]init];
//            [radioDetail.playInfo.userinfo setValuesForKeysWithDictionary:model.playInfo[@"userinfo"]];
            radioDetail.playInfo.userinfo.uname=model.playInfo[@"userinfo"][@"uname"];
            NSLog(@"音乐的名字%@",model.playInfo[@"userinfo"][@"uname"]);
            NSLog(@"为啥是个空值？？？%@",radioDetail.playInfo.userinfo.uname);
            radioDetail.tingid=model.tingid;
            
            radioDetail.title=model.title;
            NSLog(@"title也是个空值？？？%@",radioDetail.title);
            [arr addObject:radioDetail];
            
          
        }
        NSLog(@"我要的数据为啥不出来%@",arr);
        test.listTableViewController.dataSourceArray=arr;
        
        [test.listTableViewController.tableView reloadData];
//        _listTableViewController.dataSourceArray=
     
    };
    _hostessOtherWorksView.radionInfo=self.radionInfoModel;
    _hostessOtherWorksView.backgroundColor=[UIColor whiteColor];
    [_mainScrollerView addSubview:_hostessOtherWorksView];
    [self.view addSubview:_mainScrollerView];
    _lineView=[[UIView alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT-70, SCREEN_WIDTH, 1)];
    _lineView.backgroundColor=[UIColor grayColor];
    [self.view addSubview:_lineView];
    _palyerControlView=[[UIView alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT-69, SCREEN_WIDTH, 70)];
    _palyerControlView.backgroundColor=[UIColor whiteColor];
    _beforeSongButton=[UIButton buttonWithType:UIButtonTypeCustom];
    [_beforeSongButton setImage:[UIImage imageNamed:@"beforeSong"] forState:UIControlStateNormal];
    [_beforeSongButton  addTarget:self action:@selector(beforeSongButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    _beforeSongButton.frame=CGRectMake(60, 20, 20, 20);
    _pauseAndPlayButton=[UIButton buttonWithType:UIButtonTypeCustom];
    _pauseAndPlayButton.frame=CGRectMake(150, 15, 30, 30);
        self.isplay=YES;
    [_pauseAndPlayButton addTarget:self action:@selector(pauseAndPlayButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [_pauseAndPlayButton setImage:[UIImage imageNamed:@"playAndPause"] forState:UIControlStateNormal];
    _nextSongButton=[UIButton buttonWithType:UIButtonTypeCustom];
    _nextSongButton.frame=CGRectMake(250, 20, 20, 20);
    [_nextSongButton addTarget:self action:@selector(nextSongButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [_nextSongButton setImage:[UIImage imageNamed:@"nextSong"] forState:UIControlStateNormal];
    [_palyerControlView addSubview:_beforeSongButton];
    [_palyerControlView addSubview:_pauseAndPlayButton];
    [_palyerControlView addSubview:_nextSongButton];
    [self.view addSubview:_palyerControlView];
   
//    NSArray *musicArray=@[self.musicUrl];
    if (self.radioModel.tingid!=nil) {
         PKPlayerManager *manager=[PKPlayerManager shareManager];
        [manager setManagerMusicArray:self.musicArray];
        [manager playWithIndex:self.songNumber];
    }
    
   [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(changeSong:) name:@"changSong" object:@"PKPlayListTableViewController"]; 
}
-(void)changeSong:(NSNotification *)notification
{
    NSInteger count=((NSIndexPath *)notification.userInfo[@"indexpath"]).row;
    NSString *tingid=(NSString *)notification.userInfo[@"tingid"];
    
//    if (self.musicArray.count==1&&count>1) {
//        self.radioModel.tingid=((PKMainLessonMoreting *)self.dataSourceArr[count]).tingid;
//        NSLog(@"%@",self.radioModel.tingid) ;
//        [self acquireData];
//        NSString *musicUrl=self.mainLessonModel.playInfo.musicUrl;
//        NSLog(@"音乐播放得musicurl%@",self.mainLessonModel.playInfo.musicUrl);
//        NSMutableArray *musicArr=[NSMutableArray arrayWithCapacity:0];
//        [musicArr addObject:musicUrl];
//        self.musicArray =musicArr;
//        PKPlayerManager *manager=[PKPlayerManager shareManager];
//        [manager setManagerMusicArray:self.musicArray];
//        [manager playWithIndex:0];
//
//    }
//else

    self.radioModel.tingid=tingid;
   
    [self acquireData];
   
   

    

}
/**上一首*/
-(void)beforeSongButtonAction:(UIButton *)button

{
    if ([[PKPlayerManager shareManager]playIndex]==0) {
        self.playIndexCount=0;
    }
    else
    {
         self.playIndexCount=[[PKPlayerManager shareManager]playIndex]-1;
    }
   
    
    [[NSNotificationCenter defaultCenter]postNotificationName:@"beforeSongMessage" object:@"PKPKPlayViewController" userInfo:[NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"%ld",self.playIndexCount] forKey:@"plaindex"]];
        self.radioModel.tingid=((PKRadioDetailModel *)self.dataSourceArray[self.playIndexCount]).tingid;
    [self acquireData];
    [[PKPlayerManager shareManager]beforeMusic];

}
/**播放和暂停*/
-(void)pauseAndPlayButtonAction:(UIButton *)button
{
    //当点击下一首的时候首先得到当前播放的下标，然后把当前播放的下标减1，传给播放的列表界面，当前播放的下标0，就把下标为0的数组给播放列表界面

    if (self.isplay) {
        [_pauseAndPlayButton setImage:[UIImage imageNamed:@"playAndPause"] forState:UIControlStateNormal];
    }
    else
    {
        [self.pauseAndPlayButton setImage:[UIImage imageNamed:@"pauseBuuton"] forState:UIControlStateNormal];
        
        
    }
    self.isplay=!self.isplay;
    [[PKPlayerManager shareManager]playAndPause];
}
/**下一首*/
-(void)nextSongButtonAction:(UIButton *)button
{
    //当点击下一首的时候首先得到当前播放的下标，然后把当前播放的下标加1，传给播放的列表界面，当前播放的下标等于整个音乐数组count时，就传数组的count给播放列表界面
    if ([[PKPlayerManager shareManager]playIndex]==self.musicArray.count-1) {
        self.playIndexCount=self.musicArray.count-1;
    }
    else
    {
        self.playIndexCount=[[PKPlayerManager shareManager]playIndex]+1;
    }


    [[NSNotificationCenter defaultCenter]postNotificationName:@"nextSongMessage" object:@"PKPKPlayViewController" userInfo:[NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"%ld", self.playIndexCount] forKey:@"plaindex"]];
    self.radioModel.tingid=((PKRadioDetailModel *)self.dataSourceArray[self.playIndexCount]).tingid;
    [self acquireData];
   
    [[PKPlayerManager shareManager]nextMusic];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
